<?php
namespace Weibo\Model;
use Common\Model\BaseModel;

/**
 * 微博模型
 * @author Baiyu
 */
class WeiboModel extends BaseModel {
	
	private $processDeleted = FALSE;
	
	/**
	 * 这个方法配合processDeleted属性再配合_after_select, 可以实现让已删除的微博只返回deleted字段
	 */
	public function processDeleted() {
		$this -> processDeleted = TRUE;
		return $this;
	}
	
	protected function _after_select(&$resultSet,$options) {
		parent::_after_select($resultSet, $options);
		if ($this -> processDeleted) {
			foreach ($resultSet as $k => $v) {
				$resultSet[$k] = $v['deleted'] ? array('deleted' => $v['deleted']) : $v;
			}
			
			$this -> processDeleted = FALSE;
		}
	}
	
	/**
	 * 根据weibo_ids获取微博列表
	 * @param	array	$weibo_ids			要为哪些id的微博
	 * @param	boolean	$process_deleted	是让已删除的微博只返回deleted字段
	 * @param	boolean	$weibo_id_as_key	是否让weibo_id做为结果数组的键
	 * @param	number	$offset				起始行
	 * @param	number	$limit				取几行
	 * @return	array
	 */
	public function getWeiboByIds($weibo_ids = array(), $process_deleted = FALSE, $weibo_id_as_key = TRUE, $offset = 0, $limit = 0) {
		
		$return = array();				//返回数据
		$exist_weibo_ids = array();		//存在的weibo的ids
		$deleted = array();				//不存在的weibo_ids
		$deleted_data = array();		//不存在的weibo_ids组成的数组,待合并到return
		
		if (is_array($weibo_ids) && !empty($weibo_ids)) {
			$this -> where(array('weibo_id' => array('IN', $weibo_ids)));
			
			if ($limit) {
				$this -> limit($offset, $limit);
			}
			
			$list = $this -> select();
			if (!empty($list)) {
				foreach ($list as $item) {
					if ($process_deleted && $item['deleted']) {
						$item = array('weibo_id' => $item['weibo_id'], 'deleted' => $item['deleted']);
					}
					if ($weibo_id_as_key) {
						$return[$item['weibo_id']] = $item;
					} else {
						$return[] = $item;
					}
					$exist_weibo_ids[] = $item['weibo_id'];
				}
				//是否有部分微博已不存在于数据库,处理后输入量(weibo_ids数量)等于输出量(return数量)
				if (count($list) < count($weibo_ids)) {
					$deleted = array_diff($weibo_ids, $exist_weibo_ids);
					$deleted_data = array();
					foreach ($deleted as $deleted_weibo_id) {
						//未知删除原因,已经不在数据库中,所以deleted=1
						if ($weibo_id_as_key) {
							$deleted_data[$deleted_weibo_id] = array('weibo_id' => $deleted_weibo_id, 'deleted' => 1);
						} else {
							$deleted_data[] = array('weibo_id' => $deleted_weibo_id, 'deleted' => 1);
						}
					}
					
					//TODO 合并到return
				}
			} else {
				$return = $list;
			}
		}
		
		return $return;
	}

	/**
	 * 删除微博
	 * @param	number	$weibo_id		微博ID
	 * @param	number	$delete_code	1已删除无原因2为作者删除3为系统删除4为举报删除
	 * @return	boolean | array
	 */
	public function deleteById($weibo_id, $delete_code = 1, $completely = FALSE) {
		$error = 0;
		$error_msg = '';
		$result = FALSE;
		$log_array = array();
		
		$weibo = $this -> find($weibo_id);
		
		if (empty($weibo)) {
			$error = 102;
			$error_msg = '没有这条微博';
		} elseif ($weibo['deleted'] && !$completely) {
			$error = 102;
			$error_msg = '没有这条微博';
		} elseif (isset($this -> extendData['user_id']) && $weibo['user_id'] != $this -> extendData['user_id']) {
			$error = 202;
			$error_msg = '没有操作权限';
		} else {
			if (isset($this -> extendData['user_id']) && $this -> extendData['user_id'] == $weibo['user_id']) {
				$delete_code = 2;	//作者删除
			}
			
			//微博标记deleted状态
			if ($completely) {
				$result = $this -> where(array('weibo_id' => $weibo_id)) -> delete();
			} else {
				$result = $this -> where(array('weibo_id' => $weibo_id)) -> save(array('deleted' => $delete_code));
			}
			if (!$result) {
				$log_array['step'] = '3.1';
				$log_array['err_msg'] = '删除微博出错';
			}
			
			//删除index_feed
			$result && $result = FALSE !== D('WeiboIndexFeed') -> where(array('weibo_id' => $weibo_id)) -> delete();
			if (!$result) {
				$log_array['step'] = '3.2';
				$log_array['err_msg'] = '删除index_feed出错';
			}
			
			//添加deleted_feed
			if ($completely) {
				$result && $result = FALSE !== D('WeiboDeleteFeed') -> where(array('weibo_id' => $weibo_id)) -> delete();
			} else {
				$result && $result = TRUE && D('WeiboDeleteFeed') -> add(array(
						'weibo_id' => $weibo_id,
						'author_id' => $weibo['user_id'],
						'deleted' => $delete_code,
						'delete_time' => NOW_TIME,
				));
			}
			if (!$result) {
				$log_array['step'] = '3.3';
				$log_array['err_msg'] = '添加delete_feed出错';
			}
			
			//标记attachment状态
			if ($completely) {
				//这里把attachment记录标记为待删除文件,然后resource服务器那边定期清理文件并删除记录
				$result && $result = FALSE !== D('WeiboAttachment') -> where(array('weibo_id' => $weibo_id)) -> save(array('deleted' => -1));
			} else {
				$result && $result = FALSE !== D('WeiboAttachment') -> where(array('weibo_id' => $weibo_id)) -> save(array('deleted' => $delete_code));
			}
			if (!$result) {
				$log_array['step'] = '3.4';
				$log_array['err_msg'] = '删除微博附件出错';
			}
			
			//标记comment状态
			if ($completely) {
				$result && $result = FALSE !== D('WeiboComment') -> where(array('weibo_id' => $weibo_id)) -> delete();
			} else {
				$result && $result = FALSE !== D('WeiboComment') -> where(array('weibo_id' => $weibo_id)) -> save(array('deleted' => $delete_code));
			}
			if (!$result) {
				$log_array['step'] = '3.5';
				$log_array['err_msg'] = '删除微博评论出错';
			}
			
			//标记点赞状态
			if ($completely) {
				$result && $result = FALSE !== D('WeiboPraise') -> where(array('weibo_id' => $weibo_id)) -> delete();
			} else {
				$result && $result = FALSE !== D('WeiboPraise') -> where(array('weibo_id' => $weibo_id)) -> save(array('deleted' => $delete_code));
			}
			if (!$result) {
				$log_array['step'] = '3.6';
				$log_array['err_msg'] = '删除微博点赞时出错';
			}
			
			//标记forward状态
			if ($completely) {
				$result && $result = FALSE !== D('WeiboForward') -> where(array('weibo_id' => $weibo_id, '_logic' => 'or', '_complex' => array('new_id' => $weibo_id))) -> delete();
			} else {
				$result && $result = FALSE !== D('WeiboForward') -> where(array('weibo_id' => $weibo_id, '_logic' => 'or', '_complex' => array('new_id' => $weibo_id))) -> save(array('deleted' => $delete_code));
			}
			if (!$result) {
				$log_array['step'] = '3.7';
				$log_array['err_msg'] = '删除微博转发时出错';
			}
			
			//删除at
			$result && $result = FALSE !== D('WeiboAt') -> where(array('weibo_id' => $weibo_id)) -> delete();
			if (!$result) {
				$log_array['step'] = '3.8';
				$log_array['err_msg'] = '删除关联at记录时出错';
			}
			
			//original_weibo减少forward_count
			if (!$weibo['deleted'] && $weibo['type'] == 2) {	//判断deleted状态避免彻底删除时可能多减一次(比如先非彻底删除又彻底删除)
				$result && $result = FALSE !== $this -> where(array('weibo_id' => $weibo['original_id'])) -> save(array('forward_count' => array('exp', 'forward_count-1')));
				if (!$result) {
					$log_array['step'] = '3.9';
					$log_array['err_msg'] = '修改原始微博转发数时失败';
				}
			}
			
			//修改weibo_user的weibo_count
			if (!$weibo['deleted']) {
				$result && $result = FALSE !== D('WeiboUser') -> where(array('user_id' => $weibo['user_id'])) -> save(array('weibo_count' => array('exp', 'weibo_count-1')));
			}
			if (!$result) {
				$log_array['step'] = '3.10';
				$log_array['err_msg'] = '修改用户微博数失败';
			}
			
			//错误处理
			if (!$result) {
				$error = 101;
				$error_msg = '操作失败';
			
				$log_array['on'] = 'delete_weibo' . ($completely ? '_completely' : '');
				$log_array['weibo_id'] = $weibo_id;
				isset($this -> extendData['user_id']) && $log_array['uid'] = $this -> extendData['user_id'];
				$log_array['step'] = $log_array['step'] ?: '3';
				$log_array['err_msg'] = $log_array['err_msg'] ?: '操作失败';
				weibo_log($log_array);
			}
			
			//TODO 已删除的微博如何管理？多长时间后自动清除？
			
		}
		
		return array(
			'error' => $error,
			'error_msg' => $error_msg,
		);
	}
}
